<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="菜单名字" prop="titleName">
              <el-input v-model="queryParams.titleName" placeholder="请输入菜单名字" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tabs v-model="activeName" class="demo-tabs"  @tab-change="handleTabClick">
      <el-tab-pane v-for="item in service_type" :label="item.label" :name="item.value"></el-tab-pane>
    </el-tabs>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['shopping:menu:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="menuList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="菜单名字" align="center" prop="titleName" />

        <el-table-column label="菜单LOGO" align="center" prop="imgUrlPath">
          <template #default="scope">
            <el-image :src="scope.row.linkLogoPath" style="width:100px;" :zoom-rate="1.2" :max-scale="7"
                      :min-scale="0.2" :initial-index="0" :preview-teleported="true"
                      :preview-src-list="[scope.row.linkLogoPath]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="显示在首页" align="center" prop="isShowFirst">
          <template #default="scope">
            <dict-tag :options="show_status" :value="scope.row.isShowFirst" />
          </template>
        </el-table-column>
<!--        <el-table-column label="位置分类" align="center" prop="categoryType">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="service_type" :value="scope.row.categoryType" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="菜单类型" align="center" prop="menuType">
          <template #default="scope">
            <dict-tag :options="menu_type" :value="scope.row.menuType" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="是否是默认的首页   0 - 其他  1 - 默认" align="center" prop="isDefault" />-->
        <el-table-column label="链接地址" align="center" prop="linkUrl" />
        <!--        <el-table-column label="小程序的绑定点击事件" align="center" prop="bindTap" />-->
        <!--        <el-table-column label="是否是更多链接" align="center" prop="isMoreLink" />-->
        <el-table-column label="完成度" align="center" prop="isBuild" />
        <!--        <el-table-column label="商家服务子类" align="center" prop="productTypeId" />-->
        <!--        <el-table-column label="是否是跳转其他微信小程序的链接" align="center" prop="isWxMini" />-->
        <!--        <el-table-column label="其他小程序的appid" align="center" prop="otherAppId" />-->

        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shopping:menu:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shopping:menu:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改小程序首页菜单入口对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单名字" prop="titleName">
              <el-input v-model="form.titleName" placeholder="请输入菜单名字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="linkUrl">
              <el-input v-model="form.linkUrl" placeholder="请输入链接地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点击事件" prop="bindTap" >
              <el-input v-model="form.bindTap" placeholder="请输入点击事件" size="mini" style="width:100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示在首页" prop="isShowFirst">
              <el-radio-group v-model="form.isShowFirst" size="mini">
                <el-radio :value="0" :label="0">不显示</el-radio>
                <el-radio :value="1" :label="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示更多" prop="isMoreLink">
              <el-radio-group v-model="form.isMoreLink" size="mini">
                <el-radio :value="0" :label="0">否</el-radio>
                <el-radio :value="1" :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否在建设中" prop="isBuild">
              <el-radio-group v-model="form.isBuild" size="mini">
                <el-radio :value="0" :label="0">建设中</el-radio>
                <el-radio :value="1" :label="1">已完成</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state" size="mini" style="width: 100%;">
                <el-radio v-for="item in sys_normal_disable"
                          :label="item.label"
                          :value="parseInt(item.value)"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="商家服务子类" prop="productTypeId">-->
<!--              <el-input v-model="form.productTypeId" placeholder="请输入商家服务子类" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="跳转小程序" prop="isWxMini">
              <el-radio-group v-model="form.isWxMini" size="mini">
                <el-radio :value="0" :label="0">本小程序页面</el-radio>
                <el-radio :value="1" :label="1">其他小程序</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isWxMini == 1">
            <el-form-item label="小程序APPID" prop="otherAppId" >
              <el-input v-model="form.otherAppId" placeholder="请输入跳转的小程序APPID" style="width:100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图标" prop="linkLogoPath" >
              <single-pic v-model="form.linkLogoPath" type="image" :img-list="[form.linkLogoPath]" @handleChecked="chooseImg" :uploadType="2"
                          :num="1" :width="120" :height="120" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Menu" lang="ts">
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from '@/api/shopping/titlemenu';
import { MenuVO, MenuQuery, MenuForm } from '@/api/shopping/titlemenu/types';

import SinglePic from "@/components/SingleMaterial/single.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, menu_type, service_type, show_status } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'menu_type', 'service_type', 'show_status'));


const menuList = ref<MenuVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const activeName = ref('first')

const queryFormRef = ref<ElFormInstance>();
const menuFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MenuForm = {
  id: undefined,
  titleName: undefined,
  isHot: undefined,
  sort: undefined,
  state: undefined,
  isShowFirst: undefined,
  linkLogo: undefined,
  categoryType: undefined,
  menuType: undefined,
  isDefault: undefined,
  linkUrl: undefined,
  bindTap: undefined,
  isMoreLink: undefined,
  isBuild: undefined,
  productTypeId: undefined,
  isWxMini: undefined,
  otherAppId: undefined,
  linkLogoPath: undefined,
}
const data = reactive<PageData<MenuForm, MenuQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    titleName: undefined,
    isHot: undefined,
    sort: undefined,
    state: undefined,
    isShowFirst: undefined,
    linkLogo: undefined,
    categoryType: undefined,
    menuType: undefined,
    isDefault: undefined,
    linkUrl: undefined,
    bindTap: undefined,
    isMoreLink: undefined,
    isBuild: undefined,
    productTypeId: undefined,
    isWxMini: undefined,
    otherAppId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    titleName: [
      { required: true, message: "菜单名字不能为空", trigger: "blur" }
    ],
    isHot: [
      { required: true, message: "是否是Hot不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
    state: [
      { required: true, message: "请选择状态", trigger: "blur" }
    ],
    isShowFirst: [
      { required: true, message: "请选择是否显示首页", trigger: "blur" }
    ],
    categoryType: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    menuType: [
      { required: true, message: "请选择菜单页的类型", trigger: "change" }
    ],
    isDefault: [
      { required: true, message: "请选择是否是默认", trigger: "blur" }
    ],
    isMoreLink: [
      { required: true, message: "是否是更多链接不能为空", trigger: "blur" }
    ],
    isBuild: [
      { required: true, message: "是否在建设中不能为空", trigger: "blur" }
    ],
    productTypeId: [
      { required: true, message: "商家服务子类不能为空", trigger: "blur" }
    ],
    isWxMini: [
      { required: true, message: "是否是跳转其他微信小程序的链接不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询小程序首页菜单入口列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMenu(queryParams.value);
  menuList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

const handleTabClick = (type: string) => {
  queryParams.value.categoryType = type;
  form.value.categoryType = type;
  getList();
}

const chooseImg = (data) => {
  console.log("menu chooseImg",data);
  if(data.length > 0) {
    form.value.linkLogoPath = data[0].imgUrl;
    form.value.linkLogo = data[0].url;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  menuFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MenuVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加小程序首页菜单入口";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MenuVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getMenu(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改小程序首页菜单入口";
}

/** 提交按钮 */
const submitForm = () => {
  menuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMenu(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addMenu(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MenuVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除小程序首页菜单入口编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delMenu(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('shopping/menu/export', {
    ...queryParams.value
  }, `menu_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  queryParams.value.categoryType = 'first';
  form.value.categoryType = 'first';
  getList();
});
</script>
<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
